using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;

using LogAnalyzerIIS.Objects;

namespace LogAnalyzerIIS.WizardForms
{
	public partial class ServerListForm : Form
	{
		private List<ServerRecord> serverNames = new List<ServerRecord>();

		/// <summary>
		/// A list if server records
		/// </summary>
		public List<ServerRecord> ServerNames
		{
			get { return serverNames; }
		}

		public ServerListForm(CheckedListBox.ObjectCollection currentServerList)
		{
			InitializeComponent();
			serverNames.Clear();

			try
			{
				// get domain of the current computer
				string prefix = "WinNT://" + System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
				DirectoryEntry directory = new DirectoryEntry(prefix);

				// iterate through AD entries and fill the list with servers 
				foreach (DirectoryEntry directoryEntry in directory.Children)
				{
					if (directoryEntry.SchemaClassName == "Computer")
					{
						bool found = false;

						// if server already exists in the session, skip its adding
						foreach (ServerRecord server in currentServerList)
						{
							if (server.Name == directoryEntry.Name)
							{
								found = true;
								break;
							}
						}

						// if server doesn't already exist in the session, add it to the list
						if (!found)
						{
							ServerRecord server = new ServerRecord();
							server.Name = directoryEntry.Name;
							server.Path = "\\\\" + directoryEntry.Path.Substring(prefix.Length + 1);
							lbAvailableServers.Items.Add(server);
						}
					}
				}
			}
			catch
			{
				MessageBox.Show("Cannot enumerate domain's servers. Please Add them manually");
			}
		}


		private void chkAddManually_CheckedChanged(object sender, EventArgs e)
		{
			if (chkAddManually.Checked)
			{
				lblServerName.Enabled = true;
				txtServerName.Enabled = true;
				lbAvailableServers.Enabled = false;
				lblAvailableServers.Enabled = false;
			}
			else
			{
				lblServerName.Enabled = false;
				txtServerName.Enabled = false;
				lbAvailableServers.Enabled = true;
				lblAvailableServers.Enabled = true;
			}
		}


		private void btnOk_Click(object sender, EventArgs e)
		{
			serverNames.Clear();

			if (chkAddManually.Checked)
			{
				if (txtServerName.Text.Trim() != "")
				{
					ServerRecord server = new ServerRecord();
					server.Name = txtServerName.Text;
					serverNames.Add(server);
				}
			}
			else
			{
				foreach (Object server in lbAvailableServers.CheckedItems)
					serverNames.Add((ServerRecord)server);
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}